package frisk

import (
	"fmt"
	"net/http/cookiejar"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"time"

	"oschina.net/justin.qin/baidu_sign/common"
)

// StatInfo 统计信息
type StatInfo struct {
	Name    string //昵称
	Theme   int    //主题贴
	Reply   int    //回复
	InReply int    //楼中楼
	Score   int    //得分
}

// ByScore []StatInfo
type ByScore []StatInfo

func (a ByScore) Len() int           { return len(a) }
func (a ByScore) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
func (a ByScore) Less(i, j int) bool { return a[i].Score > a[j].Score }

var statInfo []StatInfo

var stat = make(map[string]int) //昵称，索引

func checkErr(err error, info string) {
	if err != nil {
		fmt.Println(info)
		panic(err)
	}
}

// Top 获取昨日活跃吧友
func Top(ptrCookieJar *cookiejar.Jar) {
	pn := 0
	yesterday := time.Now().Add(time.Hour * -24)
	date := fmt.Sprintf("%d-%d", int(yesterday.Month()), yesterday.Day())
	var urls []string

	//获取最后发帖时间是昨天的贴子的url
	for pn < 10 {
		tieba, err := common.Fetch("http://tieba.baidu.com/f?kw=linux&mo_device=1&pn="+fmt.Sprintf("%d", pn*50), nil, ptrCookieJar)
		pn++
		checkErr(err, fmt.Sprintf("获取贴吧第%d页出错\n", pn))
		fmt.Printf("贴吧第%d页\n", pn)
		reg := regexp.MustCompile(`(?s)li class="tl_shadow">.*?</li>`) //获取所有贴子
		tlShadow := reg.FindAllString(tieba, -1)
		url := ""
		for _, subShadow := range tlShadow {
			url = eachPost(subShadow, date)
			if url == "not yet" {
				continue
			} else if url == "out of date" {
				break
			} else {
				urls = append(urls, url)
			}
		}
		if url == "out of date" {
			break
		}
	}

	for i := range urls {
		theme(urls[i], date, ptrCookieJar)
	}
	topInfo := "本吧昨日（" + date + "）活跃排行榜\n" + scoreSort()
	fmt.Println(topInfo)
	return
}

func eachPost(tlShadow, date string) string {
	reg := regexp.MustCompile(`(?s)href="/p/(\d+)\?.*?<span class="ti_time">(\d{1,2}-\d{1,2})</span>`) //获取每个贴子的href和最后回复时间
	shadowInfo := reg.FindAllStringSubmatch(tlShadow, -1)
	n := len(shadowInfo)
	for i := 0; i < n; i++ {
		if shadowInfo[i][2] == date {
			return shadowInfo[i][1]
		}
		return "out of date"
	}
	return "not yet"
}

func theme(url, date string, ptrCookieJar *cookiejar.Jar) {
	// fmt.Println(url)
	tieba, err := common.Fetch("http://tieba.baidu.com/p/"+url+"?fr=wap&tb_device=pc&ie=utf-8", nil, ptrCookieJar)
	checkErr(err, "PC访问贴子出错")
	reg := regexp.MustCompile(`共<span class="red">(\d+)</span>页</li>`) //获取贴子页数
	pageInfo := reg.FindStringSubmatch(tieba)
	n, _ := strconv.Atoi(pageInfo[1])
	// fmt.Println("贴子页数", n)
	for i := 0; i < n; i++ {
		tiezi, err := common.Fetch("http://tieba.baidu.com/p/"+url+"?lp=5028&mo_device=1&is_jingpost=0&pn="+fmt.Sprintf("%d", i*50), nil, ptrCookieJar)
		checkErr(err, "访问主题贴出错")
		reg := regexp.MustCompile(`(?s)<li tid=.*?</li>`) //获取所有楼层
		floors := reg.FindAllString(tiezi, -1)
		// fmt.Println("楼层数：", len(floors))
		for i := range floors {
			is1L := false
			if i == 0 {
				is1L = true
			}
			//fmt.Println("is1L:", is1L, "i:", i)
			statistics(floors[i], date, is1L)
		}
	}
}

func statistics(floor, date string, is1L bool) {
	reg := regexp.MustCompile(`(?s)"\sclass="user_name\s?">(.*?)</a>.*?class="list_item_time">([\d-:\s]+)</span>`) //获取每楼层昵称和时间
	floorInfo := reg.FindAllStringSubmatch(floor, -1)
	n := len(floorInfo)
	for i := 0; i < n; i++ {
		if strings.Contains(floorInfo[i][2], date) {
			name := floorInfo[i][1]
			j, ok := stat[name]
			if !ok {
				j = len(stat)
				// fmt.Println("map lenth:", j)
				stat[name] = j
				subStatInfo := StatInfo{Name: name}
				statInfo = append(statInfo, subStatInfo)
				// fmt.Println("subStatInfo:", subStatInfo)
			}
			switch {
			case is1L:
				statInfo[j].Theme++
			case i == 0:
				statInfo[j].Reply++
			default:
				statInfo[j].InReply++
			}
		} else {
			continue
		}
	}
}

func scoreSort() string {
	nTheme, nReply, nInReply, s := 0, 0, 0, "排名====昵称====发贴数====回贴数====楼中楼回复====得分\n"
	for i := range statInfo {
		nTheme, nReply, nInReply = nTheme+statInfo[i].Theme, nReply+statInfo[i].Reply, nInReply+statInfo[i].InReply
		statInfo[i].Score = statInfo[i].Theme*4 + statInfo[i].Reply*2 + statInfo[i].InReply
	}
	sort.Sort(ByScore(statInfo))

	for i := 0; i < 10; i++ { // Top10
		s += fmt.Sprintf("%d、 @%s == %d == %d == %d == %d\n", i+1, statInfo[i].Name, statInfo[i].Theme, statInfo[i].Reply, statInfo[i].InReply, statInfo[i].Score)
	}
	s = fmt.Sprintf("总发贴数：%d == 总回贴数：%d == 总楼中楼回复：%d\n", nTheme, nReply, nInReply) + s
	return s
}

//获取页面中所有贴子，使用android的UA
//<li class="tl_shadow">.*?</li>

//获取每个贴子的href和最后回复时间
//href="/p/(\d+)\?.*?<span class="ti_time">(\d{1,2}-\d{1,2})</span>

//判断最后回复时间是否为昨日，是：进入贴子，统计详细；否：返回

//获取所有楼层
//共<span class="red">(\d+)</span>页</li>
//<li tid=.*?</li>

//获取每楼层昵称和时间
//class="user_name\s?">(.*?)</a>.*?class="list_item_time">([\d-:\s]+)</span>

//判断最后回复时间是否为昨日，是：加入统计；否：返回

//统计：map(索引,昵称),索引对应friskInfo数组

//1970-01-01 08:00:00 +0800 CST
//ti:六道是不是察觉什么了	//标题
//co:不然怎么会突然产生恶意呢	//内容
//_t:	1437730676483
//		1437738131864
//tag:11
//fid:14047250		//贴吧数字ID
//src:2
//word:一世之尊		//贴吧名称
//tbs:51cb03e926b7308f1437730622
//lp:5020
//hasprefix:0

//Request URL:http://tieba.baidu.com/mo/q/apubpost?_t=1437794146461
//ti:arch下goldendict无法发音
//co:我是这个情况；在mint下没问题。版本1.5
//是我那个姿势不对么？
//_t:1437794146460
//tag:11
//fid:3171
//src:2
//word:linux
//tbs:76288c8432536c1e1437794072
//lp:5020
//hasprefix:0
